package com.topisv.tms.web.stock;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.stock.ViewCusStock;
import com.topisv.tms.entity.stock.safeStock.CusStockSafe;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.stock.CusStockSafeService;
import com.topisv.tms.service.stock.ViewCusStockService;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * 安全库存
 *  Date          Author       Version       Description
 * ----------------------------------------------------------
 *  2014-7-18      CC            1.0           Create
 */
@Controller
@RequestMapping(value = "/v2/cusStockSafe")
public class CusStockSafeController extends BaseDataTableController{
	@Autowired
	private ViewCusStockService viewCusStockService;
	@Autowired
	private CusStockSafeService cusStockSafeService;
	
	@RequestMapping("toPage")
	public String toPage(Model model,HttpServletRequest request){
		fillSelectValue(model, request.getParameter("_EQ_customer.customerCode"));
		return "stock/cusStockSafe";
	}
	
	@RequestMapping(value = "query",method = RequestMethod.POST)
	public void page(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			QueryParamHolder paramHolder = collectParam(paramJson, "_");
			String flag = paramHolder.getParamMap().get("flag");
			Page<ViewCusStock> page;
			if ("query".equals(flag)) {
				page = viewCusStockService.loadViewStock(paramHolder);
			} else {
				page = viewCusStockService.loadViewStockWarning(paramHolder);
			}
			response.getWriter().print(bulidJSON(page));
		} catch (IOException e) {
			log.error("some error happened.",e);
		}
	}
	
	@RequestMapping("saveSafe")
	@ResponseBody
	public CusStockSafe saveSafe(CusStockSafe safe){
		safe.setLastmodifyTime(new Date());
		safe.setLastoperatorId(getCurUser().jobuuid);
		cusStockSafeService.save(safe);
		return safe;
	}
	private ShiroUser getCurUser(){
		return (ShiroUser) SecurityUtils.getSubject().getPrincipal();
	}
}
